package com.hetwen.remoteboot.packet;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;

import com.hetwen.remoteboot.model.MacAddr;
import com.hetwen.remoteboot.utils.PromptUtils;

public class PacketSender {

	private Context context;
	private AsyncTask<List<MacAddr>, ?, ?> task;
	
	public PacketSender(Context context) {
		this.context = context;
		task =  new PacketSendTask();
	}

	@SuppressWarnings("unchecked")
	public void send(List<MacAddr> list){
		task.execute(list);
	}
	
	private class PacketSendTask extends AsyncTask<List<MacAddr>, Void , Void>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		
		@SuppressWarnings("unchecked")
		@Override
		protected Void doInBackground(List<MacAddr>... params) {
			List<MacAddr> list = null;
			if(params != null && params.length >0){
				list = params[0];
			}
			
			if(list == null){
				return null;
			}
			
			try {
				DatagramSocket socket = new DatagramSocket();
				InetAddress address = InetAddress.getByAddress(new byte[]{(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF});
				for(int i = 0;i<list.size();i++){
					MagicPacket mp = new MagicPacket(list.get(i).mac);
					byte[] packet = mp.getMagicPacketBytes();
					DatagramPacket datagramPacket = new  DatagramPacket(packet, packet.length , address , 1);
					socket.send(datagramPacket);
				}
				socket.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			PromptUtils.showShortToast(context, "魔幻数据包发送完毕！");
		}
	}
}
